package com.libra.assemble.xutil.persistence;

import com.google.common.collect.Maps;
import com.libra.assemble.xutil.Utils;
import com.libra.assemble.xutil.enums.Operator;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Map.Entry;

/**
 * 查询条件信息.
 * (用于构建动态查询)
 *
 * @author Libra
 */
public class SearchFilter {

    /**
     * 字段名
     */
    public String fieldName;

    /**
     * 值
     */
    public Object value;

    /**
     * 查询操作
     */
    public Operator operator;

    public SearchFilter(String fieldName, Operator operator, Object value) {
        this.fieldName = fieldName;
        this.value = value;
        this.operator = operator;
    }

    /**
     * searchParams中Key的格式为:Operator_字段名.
     * 如果Key中包含多个下划线，则将第二个之后的下划线更改为点'.' 表示字段属性.
     */
    public static Map<String, SearchFilter> parse(Map<String, Object> searchParams) {
        Map<String, SearchFilter> filters = Maps.newHashMap();

        if (searchParams != null) {
            for (Entry<String, Object> entry : searchParams.entrySet()) {
                // 过滤掉空值
                String key = entry.getKey();
                Object value = entry.getValue();
                if (StringUtils.isBlank((String) value)) {
                    continue;
                }

                // 拆分operator与filedAttribute
                String[] names = StringUtils.split(key, "_");
                if (names.length != 2 && names.length != 3 && names.length != 4) {
                    throw new IllegalArgumentException(key + " is not a valid search filter name");
                }
                String filedName = names[1];
                if (names.length == 3) {
                    filedName = filedName + "." + names[2];
                }
                if (names.length == 4) {
                    filedName = filedName + "." + names[2] + "." + names[3];
                }
                Operator operator = Operator.valueOf(names[0]);

                if (filedName.indexOf("date") >= 0 || filedName.indexOf("Date") >= 0 || filedName.indexOf("time") >= 0 || filedName.indexOf("Time") >= 0) {
                    value = Utils.parseDate(value.toString());
                }
                // 创建searchFilter
                SearchFilter filter = new SearchFilter(filedName, operator, value);
                filters.put(key, filter);
            }
        }

        return filters;
    }
}
